<?php

namespace App\Http\Controllers\Entity\Pm;

use App\Classes\Publish\Publication;
use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Pm\PriceRequest;
use App\Jobs\Publish\PriceJob;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Common\CatData\Video\Vccat;
use App\Models\Common\CatData\Video\Vccattag;
use App\Models\Entity\Asset\Vlive\Vchan;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Pm\ExpiryDate;
use App\Models\Entity\Pm\MeteringPeriod;
use App\Models\Entity\Pm\Pmtag;
use App\Models\Entity\Pm\Price;
use App\Models\Entity\Pm\PriceVasseti;
use App\Models\Entity\Pm\PriceVchan;
use App\Repositories\Entity\Pm\PriceRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;

class PriceController extends Controller
{
    use ModelForm;

    /** @var  PriceRepository */
    private $priceRepository;

    public function __construct(PriceRepository $priceRepo)
    {
        $this->priceRepository = $priceRepo;
    }

    /**
     * Display a listing of the Price.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('entity.pm.prices.index_header'));
            $content->description(__('entity.pm.prices.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new Price.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.pm.prices.create_header'));
            $content->description(__('entity.pm.prices.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Price in storage.
     *
     * @param PriceRequest $request
     *
     * @return Response
     */
    public function store(PriceRequest $request)
    {
        $input = $request->all();

        if ($input['type'] != 2) {
            $input['expiry_date_id'] = null;
        }

        $price = $this->priceRepository->create($input);
        if ($price) {
            // 手动添加-添加-中间表
            if (is_array($request->get('vassetis'))) {
                $price->vassetis()->sync(array_filter($request->get('vassetis')));
            }
        }
        Flash::success(__('entity.pm.prices.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.pm.prices.index'));

    }

    /**
     * Display the specified Price.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $price = $this->priceRepository->findWithoutFail($id);

        if (empty($price)) {
            Flash::error(__('entity.pm.prices.not_found'));

            return redirect(route('entity.pm.prices.index'));
        }

        return view('entity.pm.prices.show')->with('price', $price);

    }

    /**
     * Show the form for editing the specified Price.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.pm.prices.edit_header'));
            $content->description(__('entity.pm.prices.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Price in storage.
     *
     * @param  int              $id
     * @param PriceRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $price = $this->priceRepository->findWithoutFail($id);

        if (empty($price)) {
            Flash::error(__('entity.pm.prices.not_found'));

            return redirect(route('entity.pm.prices.index'));
        }

        $input = $request->all();

        $sValidators = [
            'name'           => 'required|max:100',
            'title'          => 'max:100',
            'short_desc'     => 'required|max:100',
            'prices'         => 'required|numeric|max:100',
            // 'pmtag_id'           => 'max:100',
            // 'metering_period_id' => 'required_with:pmtag_id|max:100',
            'startdate'      => 'required|date',
            'enddate'        => 'required|date',
            'type'           => 'required',
            'expiry_date_id' => 'required_if:type,2',
        ];

        $validators = [];

        // 判断是否行内编辑,只有下线的可以编辑
        $status = Price::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            'required_if' => '当单点定价类型为"单点定价"时,单点定价有效期不能为空',
        ], [
            'name'           => '名称',
            'title'          => '标题',
            'short_desc'     => '描述',
            'prices'         => '价格',
            // 'pmtag_id'           => 'max:100',
            // 'metering_period_id' => 'required_with:pmtag_id|max:100',
            'startdate'      => '有效期开始时间',
            'enddate'        => '有效期结束时间',
            'type'           => '定价类型',
            'expiry_date_id' => '单点定价有效期',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // 排序
        if ($this->handleOrderable($id, $input)) {
            return response([
                'status'  => true,
                'message' => trans('admin::lang.update_succeeded'),
            ]);
        }

        if (isset($input['type']) && $input['type'] != 2) {
            $input['expiry_date_id'] = null;
        } else if (isset($input['type']) && $input['type'] != 1) {
            $input['pmtag_id'] = null;
            $input['metering_period_id'] = null;
        }

        $price = $this->priceRepository->update($input, $id);

        if ($price) {
            // 手动添加-添加-中间表
            if (is_array($request->get('vassetis'))) {
                $price->vassetis()->sync(array_filter($request->get('vassetis')));
            }
        }
        Flash::success(__('entity.pm.prices.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.pm.prices.index'));
    }

    /**
     * Remove the specified Price from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布的才能删除
            $price = Price::where('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->first();
            if(empty($price)){
                return response()->json(['message' => '只有状态为下线且已下线发布的才可以删除', 'status' => false]);
            }
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Price::whereIn('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->pluck('id')->toArray();
            if ($flag = $this->priceRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.pm.prices.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态为下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $price = $this->priceRepository->findWithoutFail($id);

        if (empty($price)) {
            Flash::error(__('entity.pm.prices.not_found'));

            return redirect(route('entity.pm.prices.index'));
        }

        if ($flag = $this->priceRepository->delete($id)) {

            $price->vassetis()->detach();

            return response()->json(['message' => __('entity.pm.prices.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [editAsset 编辑媒资界面]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editAsset($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('添加媒资'));

            // if (Request::get('view') !== 'table') {
            //     $grid->view('admin.grid.card');
            // }
            // 剧集详情
            // $content->row($this->assetDetailsBox($id));

            // 分集数据
            $content->row($this->vassetiTab($id));
            // $content->body($this->vassetiGrid($id));
        });
    }

    // 剧集tab
    public function vassetiTab($id)
    {
        $tab = new Tab();

        $tab->add('编辑点播媒资', $this->editVasseti($id));
        $tab->add('编辑直播媒资', $this->editVchan($id));
        return $tab;
    }

    /**
     * [editAsset 编辑媒资界面]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editVasseti($id)
    {
        $price = $this->priceRepository->findWithoutFail($id);

        if (empty($price)) {
            Flash::error(__('entity.pm.prices.not_found'));

            return redirect(route('entity.pm.prices.index'));
        }

        // 只能手动调用下函数
        Admin::script('entityPmPriceAsset();');
        // 分类
        $vcats = Vcat::get(['name', 'id']);
        // 归类数据
        $vcattags = Vcattag::get(['name', 'id']);
        return view('entity.pm.price.asset', ['vcats' => $vcats, 'vcattags' => $vcattags, 'price_id' => $id]);
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selectedVasset(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 定价id
            $price_id = $request->input('price_id');
            // 收费类型
            $charge_type = $request->input('charge_type');
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = PriceVasseti::whereHas('price', function ($query) use ($price_id) {
                if (!empty($price_id)) {
                    $query = $query->where('id', '=', $price_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = PriceVasseti::with(['price', 'vasseti', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('price', function ($query) use ($price_id) {
                    if (!empty($price_id)) {
                        $query = $query->where('id', '=', $price_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value, $charge_type) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })->count();

            $data['data'] = PriceVasseti::with(['price', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('price', function ($query) use ($price_id) {
                    if (!empty($price_id)) {
                        $query = $query->where('id', '=', $price_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value, $charge_type) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function vassetiData(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 定价id
            $price_id = $request->input('price_id');
            // 收费类型
            $charge_type = $request->input('charge_type');
            // var_dump($charge_type);
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->
                where(function ($query) use ($price_id) {
                if (!empty($price_id)) {
                    $query = $query->whereNotIn('id', PriceVasseti::where(['price_id' => $price_id])->pluck('vasseti_id')->toArray());
                }
            })
                ->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }

            $data['recordsFiltered'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function($query) use ($charge_type) {
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->where(function ($query) use ($search_value, $price_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($price_id)) {
                        $query = $query->whereNotIn('id', PriceVasseti::where(['price_id' => $price_id])->pluck('vasseti_id')->toArray());
                    }
                })->count();

            $data['data'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function($query) use ($charge_type) {
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', $charge_type);
                    }
                })
                ->where(function ($query) use ($search_value, $price_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($price_id)) {
                        $query = $query->whereNotIn('id', PriceVasseti::where(['price_id' => $price_id])->pluck('vasseti_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();

            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param [type] $price_id   [description]
     * @param [type] $vasseti_id [description]
     */
    public function addVasseti(Request $request)
    {
        $price_id   = $request->input('price_id');
        $vasseti_id = $request->input('vasseti_id');

        // 如果定价已经上线且发布,则不让新增、删除操作
        $data = Price::where('id', '=', $price_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该定价已上线发布,不能添加媒资!', 'status' => false]);
        }

        if (empty($price_id)) {
            return response()->json(['content' => '定价为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = PriceVasseti::where(['price_id' => $price_id, 'vasseti_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $priceVasseti             = new PriceVasseti();
                    $priceVasseti->price_id   = $price_id;
                    $priceVasseti->vasseti_id = $value;
                    if (!$priceVasseti->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = PriceVasseti::where(['price_id' => $price_id, 'vasseti_id' => $vasseti_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $priceVasseti             = new PriceVasseti();
            $priceVasseti->price_id   = $price_id;
            $priceVasseti->vasseti_id = $vasseti_id;
            $flag                     = $priceVasseti->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  [type] $price_id   [description]
     * @param  [type] $vasseti_id [description]
     * @return [type]             [description]
     */
    public function deleteVasseti(Request $request)
    {
        $price_id   = $request->input('price_id');
        $vasseti_id = $request->input('vasseti_id');

        // 如果定价已经上线且发布,则不让新增、删除操作
        $data = Price::where('id', '=', $price_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该定价已上线发布,不能删除媒资!', 'status' => false]);
        }

        if (empty($price_id)) {
            return response()->json(['content' => '定价为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = PriceVasseti::where(['price_id' => $price_id, 'vasseti_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => false]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = PriceVasseti::where(['price_id' => $price_id, 'vasseti_id' => $vasseti_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [编辑直播媒资]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editVchan($id)
    {
        // 只能手动调用下函数
        Admin::script('entityPmPriceVchan();');
        // 分类
        $vccats = Vccat::get(['name', 'id']);
        // 归类数据
        $vccattags = Vccattag::get(['name', 'id']);
        return view('entity.pm.price.vchan', ['vccats' => $vccats, 'vccattags' => $vccattags, 'price_id' => $id]);
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selectedVchan(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vccat = $request->input('vccat');
            // 分类
            $vccattag = $request->input('vccattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 定价id
            $price_id = $request->input('price_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = PriceVchan::whereHas('price', function ($query) use ($price_id) {
                if (!empty($price_id)) {
                    $query = $query->where('id', '=', $price_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = PriceVchan::with(['price', 'vchan', 'vchan.vccat', 'vchan.vcareacats', 'vchan.vlangs', 'vchan.vccattags'])
                ->whereHas('vchan.vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vchan.vccattags', function ($query) use ($vccattag) {
                    if (!empty($vccattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->whereHas('price', function ($query) use ($price_id) {
                    if (!empty($price_id)) {
                        $query = $query->where('id', '=', $price_id);
                    }
                })
                ->whereHas('vchan', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })->count();

            $data['data'] = PriceVchan::with(['price', 'vchan', 'vchan.vccat', 'vchan.vcareacats', 'vchan.vlangs', 'vchan.vccattags'])
                ->whereHas('vchan.vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vchan.vccattags', function ($query) use ($vccattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->whereHas('price', function ($query) use ($price_id) {
                    if (!empty($price_id)) {
                        $query = $query->where('id', '=', $price_id);
                    }
                })
                ->whereHas('vchan', function ($query) use ($search_value) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function vchanData(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vccat = $request->input('vccat');
            // 分类
            $vccattag = $request->input('vccattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 定价id
            $price_id = $request->input('price_id');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            // $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->
            //     where(function ($query) use ($price_id) {
            //     if (!empty($pmtag_id)) {
            //         $query = $query->whereNotIn('id', pmtagVasseti::where(['pmtag_id' => $pmtag_id])->pluck('vasseti_id')->toArray());
            //     }
            // })
            //     ->count();
            $data['recordsTotal'] = Vchan::where(function ($query) use ($price_id) {
                if (!empty($price_id)) {
                    $query = $query->whereNotIn('id', PriceVchan::where(['price_id' => $price_id])->pluck('vchan_id')->toArray());
                }
            })->count();
            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }
            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            // $data['recordsFiltered'] = Vchan::onlineStatus()->onlinePublished()->with(['vccat','vcareacats', 'vlangs','vccattags'])
                $data['recordsFiltered'] = Vchan::with(['vccat', 'vcareacats', 'vlangs', 'vccattags'])
                ->whereHas('vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vccattags', function ($query) use ($vccattag) {
                    if (!empty($vccattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->where(function ($query) use ($search_value, $price_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($price_id)) {
                        $query = $query->whereNotIn('id', PriceVchan::where(['price_id' => $price_id])->pluck('vchan_id')->toArray());
                    }
                })->count();
            // $data['data'] = Vchan::onlineStatus()->onlinePublished()->with(['vccat','vcareacats', 'vlangs','vccattags'])
                $data['data'] = Vchan::with(['vccat','vcareacats', 'vlangs','vccattags'])
                ->whereHas('vccat', function ($query) use ($vccat) {
                    if (!empty($vccat)) {
                        $query = $query->where('id', $vccat);
                    }
                })
                ->whereHas('vccattags', function ($query) use ($vccattag) {
                    if (!empty($vccattag)) {
                        $query = $query->where('vccattag_id', $vccattag);
                    }
                })
                ->where(function ($query) use ($search_value, $price_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($price_id)) {
                        $query = $query->whereNotIn('id', PriceVchan::where(['price_id' => $price_id])->pluck('vchan_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();

            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param Request $request [description]
     */
    public function addVchan(Request $request)
    {
        $price_id = $request->input('price_id');
        $vchan_id   = $request->input('vchan_id');

        // 如果定价已经上线且发布,则不让新增、删除操作
        $data = Price::where('id', '=', $price_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该定价已上线发布,不能添加媒资!', 'status' => false]);
        }

        if (empty($price_id)) {
            return response()->json(['content' => '定价为空!', 'status' => false]);
        }
        if (empty($vchan_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vchan_id)) {
            foreach ($vchan_id as $value) {
                $flag = PriceVchan::where(['price_id' => $price_id, 'vchan_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $priceVchan               = new PriceVchan();
                    $priceVchan->price_id = $price_id;
                    $priceVchan->vchan_id   = $value;
                    if (!$priceVchan->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = PriceVchan::where(['price_id' => $price_id, 'vchan_id' => $vchan_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $priceVchan               = new PriceVchan();
            $priceVchan->price_id = $price_id;
            $priceVchan->vchan_id   = $vchan_id;
            $flag                           = $priceVchan->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function deleteVchan(Request $request)
    {
        $price_id = $request->input('price_id');
        $vchan_id   = $request->input('vchan_id');

        // 如果定价已经上线且发布,则不让新增、删除操作
        $data = Price::where('id', '=', $price_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该定价已上线发布,不能删除媒资!', 'status' => false]);
        }

        if (empty($price_id)) {
            return response()->json(['content' => '定价为空!', 'status' => false]);
        }
        if (empty($vchan_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vchan_id)) {
            foreach ($vchan_id as $value) {
                $flag = PriceVchan::where(['price_id' => $price_id, 'vchan_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = PriceVchan::where(['price_id' => $price_id, 'vchan_id' => $vchan_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [editprice 编辑产品包和计费周期界面]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editPmtag($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('编辑产品包和计费周期');
            // $content->description(__('entity.pm.prices.edit_description'));

            $content->body($this->pmtagForm($id)->edit($id));
        });
    }

    /**
     * [pmtagForm description]
     * @return {[type]} [description]
     */
    public function pmtagForm($id)
    {
        return Admin::form(Price::class, function (Form $form) use ($id) {
            // 设置表单提交的action
            $pmtags = pmtag::where(['online_status' => 1, 'publish_status' => 1])->pluck('name', 'id')->toArray();
            $form->select('pmtag_id', '产品包')->options(['' => '选择'] + $pmtags);
            $meteringPeriods = MeteringPeriod::pluck('name', 'id')->toArray();
            $form->select('metering_period_id', '计费周期')->options(['' => '选择'] + $meteringPeriods);
            $form->setAction(route('entity.pm.prices.update_pmtag', ['price_id' => $id]));
        });
    }

    /**
     * [updatePmtag 更新产品包和计费周期]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function updatePmtag($id, Request $request)
    {
        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'pmtag_id'           => 'required|max:100',
            'metering_period_id' => 'required|max:100',
        ], [
            // 'required' => ':attribute 不能为空',
        ], [
            'pmtag_id'           => '产品包',
            'metering_period_id' => '计费周期',
        ]);

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $price = $this->priceRepository->findWithoutFail($id);
        if (empty($price)) {
            Flash::error(__('entity.pm.prices.not_found'));

            return redirect(route('entity.pm.prices.index'));
        }

        $price = $this->priceRepository->update($request->all(), $id);

        Flash::success(__('entity.pm.prices.updated_success'));

        return redirect(route('entity.pm.prices.index'));
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form($id = null)
    {
        return Admin::form(Price::class, function (Form $form) use ($id) {

            $form->display('id', 'ID');
            $form->text('name', '名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->text('short_desc', '描述')->help('必填');
            $form->number('prices', '价格(元)');
            $form->text('sdk_price_id', '定价ID');
            // 编辑时候不能编辑,新增的时候可以编辑
            if (empty($id)) {
                $form->radio('type', '定价类型')->options(array(
                    1 => '产品包定价',
                    2 => '单点定价',
                ))->default('1');
            }
            $form->select('status', '是否在售')->options(array(
                'forSale'  => '待售',
                'inSale'   => '在售',
                'stopSale' => '停售',
            ));
            $form->number('listorder', '排序');
            $expiryDates = ExpiryDate::pluck('name', 'id')->toArray();
            $form->select('expiry_date_id', '单点定价有效期')->options(['' => '选择'] + $expiryDates);
            // $pmtags = pmtag::pluck('name', 'id')->toArray();
            // $form->select('pmtag_id', '产品包')->options(['' => '选择'] + $pmtags);
            // $meteringPeriods = MeteringPeriod::pluck('name', 'id')->toArray();
            // $form->select('metering_period_id', '计费周期')->options(['' => '选择'] + $meteringPeriods);
            // $vassetis = Vasseti::pluck('name', 'id');
            // $form->multipleSelect('vassetis', '媒资')->options($vassetis);
            $form->datetimeRange('startdate', 'enddate', '有效期')->default(['start' => date('Y-m-d H:i:s', time()), 'end' => date('Y-m-d H:i:s', time())]);
            // dd(date('Y-m-d H:i:s', time()));

            // $form->date('', '生效时间');
            // $form->date('enddate', '失效时间');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Price::class, function (Grid $grid) use ($request) {
            // 状态过滤
            Publication::statusFilter($request->input('status'), $request->input('published'), $grid);
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('entity.pm.prices.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('entity.pm.prices.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('entity.pm.prices.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('entity.pm.prices.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('entity.pm.prices.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            //添加按钮
            if (Admin::user()->cannot('entity.pm.prices.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 根据定价类型判断编辑媒资还是产品包
                $type                = $actions->row->type;
                $status              = $actions->row->status;
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                // 编辑产品包
                if ($type === 1 && $publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.pm.prices.edit_pmtag')) {
                    $actions->prepend('<a href ="' . route('entity.pm.prices.edit_pmtag', ['prices' => $id]) . '" title="编辑产品包">
                        <i class="fa fa-list"></i>
                    </a>');
                }
                // 编辑媒资
                // if ($type !== 1 && $publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.pm.prices.edit_asset')) {
                if ($type !== 1 && Admin::user()->can('entity.pm.prices.edit_asset')) {
                    $actions->prepend('<a href ="' . route('entity.pm.prices.edit_asset', ['prices' => $id]) . '" title="编辑媒资">
                        <i class="fa fa-list"></i>
                    </a>');
                }
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.pm.prices.up')) {
                    $url      = route('entity.pm.prices.up');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($status === 'stopSale' && $online_status === 1 && Admin::user()->can('entity.pm.prices.down')) {
                    $url      = route('entity.pm.prices.down');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                // 上线发布按钮
                if ($online_status === 1 && $publish_status === 0 && Admin::user()->can('entity.pm.prices.publish_one')) {
                    $url      = route('entity.pm.prices.publish_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($online_status === 0 && $publish_down_status === 0 && Admin::user()->can('entity.pm.prices.down')) {
                    $url      = route('entity.pm.prices.publish_down_one');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                }
                // 在售按钮
                if ($status !== 'inSale' && $online_status === 1 && $publish_status === 1 && Admin::user()->can('entity.pm.prices.down')) {
                    $url      = route('entity.pm.prices.in_sale');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'inSale',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="在售"><i class="fa fa-shopping-cart"></i></a>');
                }
                // 停售按钮
                if ($status === 'inSale' && Admin::user()->can('entity.pm.prices.down')) {
                    $url      = route('entity.pm.prices.stop_sale');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'stopSale',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="停售"><i class="fa fa-cart-arrow-down"></i></a>');
                }
                // 编辑按钮
                if (Admin::user()->cannot('entity.pm.prices.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.pm.prices.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑,删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (Admin::user()->cannot('entity.pm.prices.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $url2 = route('entity.pm.prices.progress');
                // 下线发布功能
                if (Admin::user()->can('entity.pm.prices.publish_down')) {
                    $url      = route('entity.pm.prices.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('entity.pm.prices.publish')) {
                    $url      = route('entity.pm.prices.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('entity.pm.prices.all_down')) {
                    $url      = route('entity.pm.prices.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('entity.pm.prices.all_up')) {
                    $url      = route('entity.pm.prices.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                // 过滤按钮
                $tools->append(new \App\Admin\Extensions\Tools\Price\PriceStatus());
                $tools->append(new \App\Admin\Extensions\Tools\Price\PricePublished());
                // 批量按钮
                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (Admin::user()->cannot('entity.pm.prices.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('entity.pm.prices.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Price\ReleasePrice('up'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.pm.prices.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Price\ReleasePrice('down'));
                    }
                    // 批量上线发布按钮
                    if (Admin::user()->can('entity.pm.prices.publish_one')) {
                        $batch->add('上线发布', new \App\Admin\Extensions\Tools\Price\ReleasePrice('publish'));
                    }
                    // 批量下线发布按钮
                    if (Admin::user()->can('entity.pm.prices.publish_down_one')) {
                        $batch->add('下线发布', new \App\Admin\Extensions\Tools\Price\ReleasePrice('publishDown'));
                    }
                    // 批量在售按钮
                    if (Admin::user()->can('entity.pm.prices.in_sale')) {
                        $batch->add('在售', new \App\Admin\Extensions\Tools\Price\ReleasePrice('inSale'));
                    }
                    // 批量停售按钮
                    if (Admin::user()->can('entity.pm.prices.stop_sale')) {
                        $batch->add('停售', new \App\Admin\Extensions\Tools\Price\ReleasePrice('stopSale'));
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable()->editable();
            $grid->column('title', '标题')->sortable()->editable();
            $grid->column('subtitle', '副标题')->sortable()->editable();
            $grid->column('short_desc', '描述')->sortable();
            $grid->column('prices', '价格(元)')->sortable()->editable();
            $grid->column('sdk_price_id', '定价ID')->sortable();
            $grid->column('status', '是否在售')->display(function ($val) {
                switch ($val) {
                    case 'inSale':
                        return '<span class="badge bg-green">在售</span>';
                        break;
                    case 'stopSale':
                        return '<span class="badge bg-gray">停售</span>';
                        break;
                    default:
                        return '<span class="badge bg-yellow">待售</span>';
                        break;
                }
            });
            // $states = [
            //     'forSale' => ['text' => '待售'],
            //     'inSale' => ['text' => '在售'],
            //     'stopSale' => ['text' => '停售'],
            // ];

            // $grid->column('status','是否在售')->switchGroup([
            //     'status' => '在售', 'status' => '停售', 'status' => '待售'
            // ], $states);
            $grid->column('type', '定价类型')->display(function ($val) {
                switch ($val) {
                    case 1:
                        return '<span class="badge bg-purple">产品包定价</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-green">单点定价</span>';
                        break;
                    default:
                        return '<span class="badge bg-yellow">未知</span>';
                        break;
                }
            });
            $grid->column('expiryDate.name', '单点定价有效期')->sortable();
            // $grid->column('pmtag.name', '产品包')->sortable();
            // $grid->column('meteringPeriod.name', '计费周期')->sortable();
            // $grid->vassetis('媒资')->pluck('name')->label();
            $grid->column('listorder', '排序')->editable()->sortable();
            $grid->column('startdate', '生效时间')->sortable();
            $grid->column('enddate', '失效时间')->sortable();
            $grid->column('created_at', '创建日期')->sortable();
            $grid->column('updated_at', '更新日期')->sortable();
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 计费周期
                $aMeteringPeriods = MeteringPeriod::pluck('name', 'id');
                $filter->equal('metering_period_id', '计费周期')->select($aMeteringPeriods);
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 价格(元)
                $filter->between('prices', '价格');
                // 生效时间
                $filter->between('startdate', '生效时间')->datetime();
                // 失效时间
                $filter->between('enddate', '失效时间')->datetime();
            });
        });
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.pm.prices.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的ids, 1:有媒资的, 2:有产品包的
        $total_num = DB::table('prices as a')
            ->join('price_vassetis as b', 'a.id', '=', 'b.price_id')
            ->where(['online_status' => 0, 'publish_down_status' => 1])
            ->pluck('a.id')->unique()->count();
        $total_num += Price::where(['type' => 1])
            ->where(['online_status' => 0, 'publish_down_status' => 1])
            ->whereNotNull('pmtag_id')->pluck('id')->count();
        $notices = [];
        // 已经上线的ids
        $notices[] = [Price::where(['online_status' => 1])->pluck('id'), 'ID为以下的定价已经上线: '];
        // 还未下线发布的ids
        $notices[] = [Price::where(['publish_down_status' => 0])->pluck('id'), 'ID为以下的定价还未下线发布: '];
        // 没有媒资的ids
        $notices[] = [DB::table('prices as a')
            ->where('type' ,'<>', 1)
            ->whereNull('deleted_at')
            ->whereNotExists(function($query) {
                $query->select(DB::raw(1))
                    ->from('price_vassetis as b')
                    ->whereRaw('a.id = b.price_id');
            })
            ->pluck('a.id'), 
            'ID为以下的定价下面没有媒资: ' 
        ];
        // 没有产品包的ids
        $notices[] = [Price::where(['type' => 1])->whereNotNull('pmtag_id')->pluck('id'), 'ID为以下的定价没有产品包: '];
        // 拼装提示信息
        $oparation  = '定价上线';
        $totalNum   = Price::count();
        $successNum = $total_num;
        $failNum    = $totalNum - $successNum;
        $content = Publication::makeNoticeInfo($oparation, $totalNum, $successNum, $failNum, $notices);
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '定价上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new PriceJob(['dispatch', 'up'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.pm.prices.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的ids
        // $total_num = Publication::getTotalNum(new Price(), ['online_status' => 1]);
        $result = Publication::getTotalNum(new Price(), [
            [['online_status' => 1], 'ID为以下定价还没上线'],
        ], '定价下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '定价下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new PriceJob(['dispatch', 'down'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.pm.prices.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的ids
        // $price_ids = Publication::getTotalIds(new Price(), ['online_status' => 1, 'publish_status' => 0]);
        $result = Publication::getTotalNum(new Price(), [
            [['online_status' => 1], 'ID为以下定价还未上线: '],
            [['publish_status' => 0], 'ID为以下定价已经上线发布: '],
        ], '定价发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        // 统计需要处理的任务的中间边相关联记录数
        // $price_vassetis = Publication::getTotal(new Pricevasseti(), 'price_id', $price_ids);
        // $total_num      = count($price_ids) + $price_vassetis;
        // 任务表插入一条记录
        $data   = ['task_type' => '定价发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new PriceJob(['dispatch', 'publish'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.pm.prices.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的ids
        // $price_ids = Publication::getTotalIds(new Price(), ['online_status' => 0, 'publish_down_status' => 0]);
        $result = Publication::getTotalNum(new Price(), [
            [['online_status' => 0], 'ID为以下定价还未下线: '], 
            [['publish_down_status' => 0], 'ID为以下定价已经下线发布: '],
        ], '定价下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        // 统计需要处理的任务的中间边相关联记录数
        // $price_vassetis = Publication::getTotal(new Pricevasseti(), 'price_id', $price_ids);
        // $total_num      = count($price_ids) + $price_vassetis;
        // 任务表插入一条记录
        $data   = ['task_type' => '定价下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new PriceJob(['dispatch', 'publishDown'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.pm.prices.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Price(), $request->ids, ['online_status' => 0, 'publish_down_status' => 1]);
                // 统计需要处理的任务的ids, 1:有媒资的, 2:有产品包的
                $ids = DB::table('prices as a')
                    ->join('price_vassetis as b', 'a.id', '=', 'b.price_id')
                    ->where(['online_status' => 0, 'publish_down_status' => 1])
                    ->whereIn('a.id', $request->ids)
                    ->pluck('a.id')->unique();
                $hasPmtagIds = Price::where(['type' => 1])->whereIn('id', $request->ids)->whereNotNull('pmtag_id')->pluck('id');
                $ids = $ids->merge($hasPmtagIds);
                $notices = [];
                // 已经上线的ids
                $notices[] = [Price::where(['online_status' => 1])->whereIn('id', $request->ids)->pluck('id'), 'ID为以下的定价已经上线: '];
                // 还未下线发布的ids
                $notices[] = [Price::where(['publish_down_status' => 0])->whereIn('id', $request->ids)->pluck('id'), 'ID为以下的定价还未下线发布: '];
                // 没有媒资的ids
                $notices[] = [DB::table('prices as a')
                    ->whereNotExists(function($query) {
                        $query->select(DB::raw(1))
                            ->from('price_vassetis as b')
                            ->whereRaw('a.id = b.price_id');
                    })
                    ->whereIn('a.id', $request->ids)
                    ->where('type' ,'<>', 1)
                    ->whereNull('deleted_at')
                    ->pluck('a.id'), 
                    'ID为以下的定价下面没有媒资: ' 
                ];
                // 没有产品包的ids
                $notices[] = [Price::where(['type' => 1])->whereIn('id', $request->ids)->whereNull('pmtag_id')->pluck('id'), 'ID为以下的定价没有产品包: '];
                // 拼装提示信息
                $oparation  = '定价上线';
                $totalNum   = count($request->ids);
                $successNum = $ids->count();
                $failNum    = $totalNum - $successNum;
                $content = Publication::makeNoticeInfo($oparation, $totalNum, $successNum, $failNum, $notices);
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 获取有媒资的单点定价和有产品包的定价的ids
                // $hasVassetiIds = PriceVasseti::whereIn('price_id', $ids)->pluck('price_id')->unique();
                // $hasPmtagIds   = Price::whereIn('id', $ids)->where(['type' => 1])->whereNotNull('pmtag_id')->pluck('id');
                // $ids           = $hasVassetiIds->merge($hasPmtagIds);
                $result        = Publication::updateMany(new Price(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '上线操作失败']);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.pm.prices.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Price(), $request->ids, ['online_status' => 1, 'publish_status' => 0]);
                $result = Publication::myfilter(new Price(), $request->ids, [
                    [['online_status' => 1], 'ID为以下定价还未上线: '],
                    [['publish_status' => 0], 'ID为以下定价已经上线发布: '],
                ], '定价发布: ');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    // 获取需要插入的产品包数和中间表记录数
                    $total_num = count($ids);
                    $data      = ['task_type' => '定价发布', 'user_id' => $user_id, 'total_num' => $total_num];
                    $taskid    = Publication::insertTasks($data);
                    dispatch(new PriceJob(['publish'], $ids, $taskid));
                    $url = route('entity.pm.prices.progress');
                    return response()->json(['status' => 'queue', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $prices              = Price::whereIn('id', $ids)->get();
                $price_vassetis      = PriceVasseti::whereIn('price_id', $ids)->get();
                $price_datas         = PriceJob::makePrices($prices);
                $price_vasseti_datas = PriceJob::makePriceVassetis($price_vassetis);
                $result1             = Publication::insertApi('prices', $price_datas);
                $result2             = Publication::insertApi('price_vassetis', $price_vasseti_datas);
                $result3             = Publication::updateMany(new Price(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                $content = ($result1 && $result2 && $result3) ? $content : '上线发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.pm.prices.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Price(), $request->ids, ['online_status' => 1]);
                $result = Publication::myfilter(new Price(), $request->ids, [
                    [['online_status' => 1], 'ID为以下定价还没上线'],
                ], '定价下线: ');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Price(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.pm.prices.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Price(), $request->ids, ['online_status' => 0, 'publish_down_status' => 0]);
                $result = Publication::myfilter(new Price(), $request->ids, [
                    [['online_status' => 0], 'ID为以下定价还未下线: '], 
                    [['publish_down_status' => 0], 'ID为以下定价已经下线发布: '],
                ], '定价下线发布: ');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $pricesCount = DB::connection('interface')->table('prices')->whereIn('price_id', $ids)->count();
                if ($pricesCount) {
                    // 删除接口库中对应的数据
                    $result1 = Publication::deleteApi('prices', 'price_id', $ids);
                } else {
                    $result1 = true;
                }
                $priceVassetisCount = DB::connection('interface')->table('price_vassetis')->whereIn('price_id', $ids)->count();
                if ($priceVassetisCount) {
                    $result2 = Publication::deleteApi('price_vassetis', 'price_id', $ids);
                } else {
                    $result2 = true;
                }
                // 更新状态
                $result3 = Publication::updateMany(new Price(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                $content = ($result1 && $result2 && $result3) ? $content : '下线发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 在售
            case 'inSale':
                if (Admin::user()->cannot('entity.pm.prices.in_sale')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Price(), $request->ids, [
                    [['online_status' => 1], 'ID为以下定价还未上线'],
                    [['publish_status' => 1], 'ID为以下定价还未发布'],
                    [[['status', '<>', 'inSale']], 'ID为以下定价已经在售'],
                ], '定价在售: ');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result1 = Publication::updateMany(new Price(), $ids, [
                    'status'  => 'inSale',
                    'user_id' => $user_id,
                ]);
                $result2 = DB::connection('interface')->table('prices')->update(['status' => 'inSale']);
                $content = ($result1 && $result2) ? $content : '在售失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 停售
            case 'stopSale':
                if (Admin::user()->cannot('entity.pm.prices.stop_sale')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Price(), $request->ids, ['status' => 'inSale']);
                $result = Publication::myfilter(new Price(), $request->ids, [
                    [['status' => 'inSale'], 'ID为以下定价还未在售: '],
                ], '定价停售');
                list($ids, $content) = $result;
                if (empty($ids)) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 更新状态
                $result1 = Publication::updateMany(new Price(), $ids, [
                    'status'  => 'stopSale',
                    'user_id' => $user_id,
                ]);
                // 更新接口库中状态
                $result2 = DB::connection('interface')->table('prices')->update(['status' => 'stopSale']);
                $content = ($result1 && $result2) ? $content : '停售失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        return Publication::progress($taskid);
    }

}
